package cn.school.pay.service.impl;

import cn.school.common.utils.RedisUtils;
import cn.school.common.utils.SysUserUtils;
import cn.school.pay.dao.IPayCertificateDao;
import cn.school.pay.service.IPayCertificateService;
import cn.school.pay.vo.PayCertificateInfoVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PayCertificateServiceImpl implements IPayCertificateService {

	@Autowired
	private IPayCertificateDao iPayCertificateMapper;
	
	@Autowired
	private RedisUtils redisUtil;
	
	@Override
	public IPage<PayCertificateInfoVO> queryPayCertificateList(PayCertificateInfoVO vo) {
		int totalCount = iPayCertificateMapper.queryPayCertificateListCount(vo);
		int startNum=(vo.getPageNum()-1)*vo.getPageSize();
		vo.setPageNum(startNum);
		List<PayCertificateInfoVO> payList =  iPayCertificateMapper.queryPayCertificateList(vo);
		IPage<PayCertificateInfoVO> page = new Page<>();
		page.setTotal(totalCount);
		page.setRecords(payList);
		return page;
	}


	@Override
	public int addPayCertificate(PayCertificateInfoVO vo) {
		vo.setCreateBy(SysUserUtils.getSysUser().getUsername());
		vo.setCreateTime(new Date());
		int num = 0 ;
		if("1".equals(vo.getIsDefault())){
			iPayCertificateMapper.updateIsDefault("0",vo.getPayCertificateType());
		}
		num= iPayCertificateMapper.addPayCertificate(vo);
		return num;
	}


	@Override
	public int updatePayCertificate(PayCertificateInfoVO vo) {
		vo.setModifyBy(SysUserUtils.getSysUser().getUsername());
		vo.setModifyTime(new Date());
		int num = 0 ;
		if("1".equals(vo.getIsDefault())){
			iPayCertificateMapper.updateIsDefault("0",vo.getPayCertificateType());
		}
		num = iPayCertificateMapper.updatePayCertificate(vo);
		return num;
	}


	@Override
	public int delPayCertificate(PayCertificateInfoVO vo) {
		return iPayCertificateMapper.delPayCertificate(vo);
	}


	@Override
	public int refreshConfigCache() {
		List<PayCertificateInfoVO> payCertficateList = iPayCertificateMapper.getDefaultPayCertficateList();
		for(PayCertificateInfoVO payCertificate :payCertficateList){
			Map<String,String> map = JSON.parseObject(JSON.toJSONString(payCertificate), Map.class);
			if("1".equals(payCertificate.getPayCertificateType())){
				redisUtil.set("AliPayConfig", map,-1);
			}else if("2".equals(payCertificate.getPayCertificateType())){
				redisUtil.set("WXPayConfig", map,-1);
			}
		}
		return 1;
	}

}
